<template lang="html">
    <div class="publicBox">
        <div class="publicBoxContent customerManagement">
            <div class="customerManagementSearch">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="收货人">
                        <el-input placeholder="请输入收货人" v-model="formInline.name"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话">
                        <el-input placeholder="请输入联系电话" v-model="formInline.mobile"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                        <el-button type="primary" @click="modifyAddress('add')">新增</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="customerManagementBox">
                <el-table :data="addRess" border style="width: 100%"  v-loading="loading"  @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="收货人">
                        <template slot-scope="scope">
                            {{scope.row.name}}
                            <div class="img" v-if="scope.$index==defaultAddress"></div>
                        </template>
</el-table-column>
<el-table-column prop="phone" label="联系电话"></el-table-column>
<el-table-column prop="id_card_number" label="身份证号码"></el-table-column>
<el-table-column prop="detail" label="地址"></el-table-column>
<el-table-column label="操作">
    <template slot-scope="scope">
                            <el-button type="text" size="small" @click="modifyAddress(scope.$index)">编辑</el-button>
                            <el-button type="text" size="small" @click="deleAddress(scope.$index,'single')">删除</el-button>
                        </template>
</el-table-column>
</el-table>
</div>
<div class="customerManagementPage">
    <div class="pageLeft">
        <el-button type="primary" @click="deleAddress(0,'multiple')">批量删除</el-button>
    </div>
    <div class="pageRight">
        <el-pagination background @current-change="handleCurrentChange" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="addressTotal">
        </el-pagination>
    </div>
</div>
</div>



<el-dialog :title="title" :visible.sync="dialogVisible" @close="handleClose">

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="收货人" prop="name">
            <el-col :span="24">
                <el-input v-model="ruleForm.name" placeholder="请输入收货人"></el-input>
            </el-col>

        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-col :span="24">
                <el-input v-model="ruleForm.phone" maxlength="11" placeholder="请输入手机号"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card_number">
            <el-col :span="24">
                <el-input v-model="ruleForm.id_card_number" placeholder="请输入身份证号码"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item label="" class="idCard">
            <el-row>
                <el-col :span="12">
                    <el-upload class="avatar-uploader" :action="imgUrl+'index.php?s=/admin/upload/image'" :headers="headers" :show-file-list="false" :auto-upload="true" name="iFile" :on-success="positiveAvatarSuccess" :on-error="err">
                        <img v-if="positiveImg" :src="positiveImg" class="avatar">
                        <img v-else src="../../assets//img/zhengmian.png" class="avatar">

                    </el-upload>
                </el-col>
                <el-col :span="12">
                    <el-upload class="avatar-uploader" :action="imgUrl+'index.php?s=/admin/upload/image'" :headers="headers" :show-file-list="false" :auto-upload="true" name="iFile" :on-success="backAvatarSuccess">
                        <img v-if="backImg" :src="backImg" class="avatar">
                        <img v-else src="../../assets//img/fanmian.png" class="avatar">

                    </el-upload>
                </el-col>
            </el-row>
        </el-form-item>
        <!--                    <el-form-item label="收货地址" prop="region">-->
        <!--                        <el-col :span="24">-->
        <!--                        <el-cascader v-model="ruleForm.region" :options="opt" placeholder="请选择省/市/区(县)"-->
        <!--                                     :props="{label : 'region_name',value : 'region_name'}"></el-cascader>-->
        <!--                        </el-col>-->
        <!--                    </el-form-item>-->

        <el-form-item label="收货地址">
            <el-col :span="24">
                <el-select v-model="cityOne" placeholder="请选择省" @change="oneCity" class="addre">
                    <el-option v-for="(item,index) in opt" :key="index" :label="item.region_name" :value="index">
                    </el-option>
                </el-select>
                <el-select v-model="cityTwo" placeholder="请选择市" @change="twoCity" class="addre">
                    <el-option v-for="(item,index) in twoArr" :key="index" :label="item.region_name" :value="index">
                    </el-option>
                </el-select>
                <el-select v-model="cityThree" placeholder="请选择区/县" class="addre">
                    <el-option v-for="(item,index) in threeArr" :key="index" :label="item.region_name" :value="index">
                    </el-option>
                </el-select>
            </el-col>
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
            <el-col :span="24">
                <el-input v-model="ruleForm.detail" placeholder="请输入详细地址"></el-input>
            </el-col>
        </el-form-item>
        <el-form-item>
            <el-col :span="24">
                <el-checkbox v-model="ruleForm.status">设为默认地址</el-checkbox>
            </el-col>
        </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
          </span>
</el-dialog>

</div>

</template>

<script>
    import {
        regionData
    } from 'element-china-area-data'
    import config from '../../config'
    export default {
        name: "customerManagement",
        data: function() {
            // 手机号验证
            const validatePhone = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入手机号"));
                } else {
                    if (!/^1[3456789]\d{9}$/.test(value)) {
                        callback(new Error("请输入正确的手机号"));
                    } else {
                        callback();
                    }
                }
            }
            return {
                loading: true,
                imgUrl: config.imgUrl,
                headers: {
                    token: ''
                },
                title: "编辑收货地址",
                cityOne: '',
                cityTwo: '',
                cityThree: '',
                twoArr: [],
                threeArr: [],
                cityIndex: null,
                ctiyChildrenIndex: null,
                formInline: {
                    name: "",
                    mobile: ""
                },
                tableData: [{}],
                multipleSelection: [],
                rules: {
                    name: [{
                        required: true,
                        message: '请输入收货人姓名',
                        trigger: 'blur'
                    }],
                    phone: [{
                        validator: validatePhone,
                        trigger: 'blur'
                    }],
                    id_card_number: [{
                        required: true,
                        message: '请输入身份证号码',
                        trigger: 'blur'
                    }],
                    detail: [{
                        required: true,
                        message: '请输入详细地址',
                        trigger: 'blur'
                    }],
                    region: [{
                        required: true,
                        message: '请选择收货城市',
                        trigger: 'change'
                    }]
                },
                currentPage: 1,
                pageSize: 15,
                dialogFormVisible: false,
                dialogVisible: false,
                labelPosition: 'right',
                positiveImg: '', //正面
                backImg: '', //反面
                options: regionData,
                opt: null,
                isaddress: [{
                    value: '0',
                    label: '否'
                }, {
                    value: '1',
                    label: '是'
                }],
                search: '',
                addRess: [],
                addressTotal: 0,
                ruleForm: {
                    name: "",
                    phone: "",
                    id_card_number: "",
                    region: [],
                    detail: "",
                    status: false,
                    id_card_just: '',
                    id_card_back: ''
                },
                id: "",
                defaultAddress: null



            }
        },
        created() {
            this.getToken();
            this.getaddRess();
            this.getAddressList();

        },
        computed: {

        },
        watch: {

            cityIndex() {
                this.twoArr = this.opt[this.cityIndex].children;
                this.threeArr = this.opt[this.cityIndex].children[this.ctiyChildrenIndex].children;
            },
            ctiyChildrenIndex() {
                this.threeArr = this.opt[this.cityIndex].children[this.ctiyChildrenIndex].children;
            }
        },
        methods: {
            oneCity(index) {
                this.cityIndex = index;
                this.ctiyChildrenIndex = 0;
                this.cityTwo = 0;
                this.cityThree = 0;
            },
            twoCity(index) {
                this.ctiyChildrenIndex = index;
                this.cityThree = 0;
            },
            getToken() {
                this.headers.token = window.localStorage.getItem("token");

            },
            getAddressList() {
                this.$HttpGet("/index.php?s=/admin/home.address/getcachetree").then(res => {
                    this.opt = res.data
                })
            },
            getaddRess() {
                this.defaultAddress = null;
                this.$HttpGet("/index.php?s=/admin/home.address/lists", {
                    search: this.search,
                    name: this.formInline.name,
                    phone: this.formInline.mobile,
                    page: this.currentPage,
                    pageSize: this.pageSize
                }).then(res => {
                    this.loading = false
                        // this.addRess = res.data.list.data;
                    this.addressTotal = res.data.list.total;

                    var arr = [''];
                    var addr = res.data.list.data;
                    var bz = true;
                    for (let i = 0; i < addr.length; i++) {
                        if (addr[i].is_status == 1) {
                            arr[0] = addr[i];
                            this.defaultAddress = 0;
                            bz = false;
                        } else {
                            arr.push(addr[i]);
                        }
                    }
                    if (bz) {
                        arr.splice(0, 1)
                    }
                    this.addRess = arr;


                    // for(let i=0;i<this.addRess.length;i++){
                    //     if(this.addRess[i].is_status==1){
                    //         this.defaultAddress=i;
                    //         break;
                    //     }
                    // }

                })
            },
            handleClose() {
                this.ruleForm = {
                    name: "",
                    phone: "",
                    id_card_number: "",
                    region: [],
                    detail: "",
                    status: false,
                    id_card_just: '',
                    id_card_back: ''
                }
                this.$refs['ruleForm'].resetFields();
            },
            confirm() {
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        let url = "";
                        if (this.id) {
                            url = `/index.php?s=/admin/home.address/edit&address_id=${this.id}`
                        } else {
                            url = "/index.php?s=/admin/home.address/add";
                        }
                        this.ruleForm.region = [
                            this.opt[this.cityOne].region_name,
                            this.opt[this.cityOne].children[this.cityTwo].region_name,
                            this.opt[this.cityOne].children[this.cityTwo].children[this.cityThree].region_name,
                        ];
                        this.$HttpPost(url, this.ruleForm).then(res => {
                            this.$notifySuccess(res.msg);
                            this.getaddRess();
                            this.dialogVisible = false;
                        })
                    }
                });
            },
            modifyAddress(id) {

                if (id == 'add') {
                    this.title = "新增收货地址";
                    this.ruleForm = {
                        name: '',
                        phone: '',
                        id_card_number: '',
                        region: '',
                        detail: '',
                        status: '',
                        id_card_just: '',
                        id_card_back: ''
                    };
                    this.positiveImg = '';
                    this.backImg = '';
                    this.dialogVisible = true;
                    this.id = '';
                    this.cityOne = null
                    this.cityTwo = null;
                    this.cityThree = null;
                    return false;
                } else {
                    this.title = "编辑收货地址";
                }

                this.id = this.addRess[id].address_id;
                this.$HttpGet("/index.php?address_id=7&s=/admin/home.address/detail", {
                    address_id: this.addRess[id].address_id
                }).then(res => {
                    for (var i = 0; i < this.opt.length; i++) {

                        if (this.opt[i].region_name == res.data.region[0]) {
                            this.cityOne = i;
                            this.cityIndex = i;
                        }
                    }
                    for (var i = 0; i < this.opt[this.cityOne].children.length; i++) {
                        if (this.opt[this.cityOne].children[i].region_name == res.data.region[1]) {
                            this.cityTwo = i;
                            this.ctiyChildrenIndex = i;

                        }
                    }
                    for (var i = 0; i < this.opt[this.cityOne].children[this.cityTwo].children.length; i++) {
                        if (this.opt[this.cityOne].children[this.cityTwo].children[i].region_name == res.data.region[2]) {
                            this.cityThree = i;
                        }
                    }
                    this.ruleForm = {
                        name: res.data.detail.name,
                        phone: res.data.detail.phone,
                        id_card_number: res.data.detail.id_card_number,
                        region: res.data.region,
                        detail: res.data.detail.detail,
                        status: res.data.detail.is_status == 1 ? true : false,
                        id_card_just: res.data.detail.id_card_just,
                        id_card_back: res.data.detail.id_card_back
                    }
                    this.backImg = res.data.detail.id_card_back;
                    this.positiveImg = res.data.detail.id_card_just;
                    this.dialogVisible = true;
                })
            },
            deleAddress(id, num) {
                var addre = null;
                if (num == 'multiple') {
                    addre = this.multipleSelection;
                }
                if (num == 'single') {
                    addre = [this.addRess[id].address_id]
                }
                if (addre.length <= 0) {
                    this.$notifyError("请选择删除选项！");
                    return false;
                }
                this.$confirm('确认移除该地址', '删除', {
                    type: 'error'
                }).then(res => {
                    this.$HttpPost("/index.php?address_id=7&s=/admin/home.address/delete", {
                        address_id: addre
                    }).then(res => {

                        this.$notifySuccess('删除成功');
                        this.getaddRess();
                    })
                })

            },
            handleSelectionChange(val) {
                this.multipleSelection = [];
                for (let i = 0; i < val.length; i++) {
                    this.multipleSelection.push(val[i].address_id)
                }

            },
            onSubmit() {
                this.getaddRess();
            },

            handleCurrentChange(val) {
                this.currentPage = val;
                this.getaddRess();
            },
            positiveAvatarSuccess(res, file) {
                console.log(res)
                if (res.code == 1) {
                    this.$notifyError(res.msg);
                    return false
                }
                this.positiveImg = res.data.file_path;
                this.ruleForm.id_card_just = res.data.file_path;
            },
            backAvatarSuccess(res, file) {
                console.log(res)
                if (res.code == 1) {
                    this.$notifyError(res.msg);
                    return false
                }
                this.backImg = res.data.file_path;
                this.ruleForm.id_card_back = res.data.file_path;
            },
            err(data) {
                debugger
            },

        }
    }
</script>

<style lang="scss" scoped>
    .customerManagement {
        .customerManagementBox {
            margin-top: 20px;
        }
        .customerManagementPage {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            margin-bottom: 50px;
        }
    }
    
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    
    .avatar {
        width: 195px;
        height: auto;
        display: block;
    }
    
    .img {
        width: 36px;
        height: 36px;
        background: url("../../assets/img/index/morendizhi.png");
        position: absolute;
        top: 0px;
        right: 0px;
    }
    
    /deep/ .el-dialog {
        min-width: 550px;
    }
    
    /deep/ .demo-ruleForm {
        .el-form-item {
            .addre {
                margin-right: 20px;
                margin-bottom: 10px;
                &:first-child {
                    margin-left: 0px;
                }
            }
            .el-form-item__label:before {
                content: '*';
                color: #F56C6C;
                margin-right: 4px;
            }
        }
        /deep/ .el-cascader {
            display: block;
        }
    }
</style>